<template>
  <div>
    <!--  2018/2/2 10:51 添加库存信息 zhangQ -->
    <Modal
      width="800"
      v-model="modalShow"
      :title="operaType=='add'?'添加库存信息':'编辑'+addInfo.poweruserName+'库存信息'">
      <Form v-if="modalShow" :model="addInfo" :label-width="120" ref="addInfo" :rules="addInfoRule">
        <Form-item label="电厂" v-if="isDcShow">
          <Select v-model="addInfo.poweruserName" placeholder="请选择电厂">
            <Option v-for="item in userNamelist" :value="item.userName" :key="item.userName">{{ item.userName }}
            </Option>
          </Select>
        </Form-item>
        <Form-item label="日期">
          <DatePicker format="yyyy年MM月dd日" :value="addInfo.startDateValue" v-model="addInfo.startDateValue"
                      :disabled="!dateValueEnable" :options="startDateOption"
                      placeholder="选择日期" style="width: 200px"></DatePicker>
        </Form-item>

        <Form-item label="日消耗量（万吨）" prop="xhl">
          <Input v-model="addInfo.xhl" placeholder="请填写消耗量(万吨)" type="number"></Input>
        </Form-item>

        <Form-item label="库存量（万吨）" prop="kcl">
          <Input v-model="addInfo.kcl" type="number" placeholder="请填写库存量(万吨)"></Input>
        </Form-item>

        <Form-item label="到达量（万吨）" prop="ddl">
          <Input v-model="addInfo.ddl" type="number" placeholder="请填写到达量(万吨)"></Input>
        </Form-item>

        <Form-item label="本季度需求（万吨）" prop="lastQuarterDemand">
          <Input v-model="addInfo.lastQuarterDemand" type="number" placeholder="请填写到达量(万吨)"></Input>
        </Form-item>

        <Form-item label="下季度需求（万吨）" prop="nextQuarterDemand">
          <Input v-model="addInfo.nextQuarterDemand" type="number" placeholder="请填写到达量(万吨)"></Input>
        </Form-item>
        <!--<Form-item>-->
        <!--<Button type="primary" @click="submitAdd('addInfo')">提交</Button>-->
        <!--<Button type="ghost" style="margin-left: 8px" @click="goBack">取消</Button>-->
        <!--</Form-item>-->
      </Form>

      <!--@on-ok="submitAdd"-->
      <!--@on-cancel="goBack"-->
      <div slot="footer">
        <Button type="primary" @click="submitAdd">确认</Button>

        <Button @click="goBack">取消</Button>
      </div>

    </Modal>
  </div>
</template>
<script>
  /**
   *  库存信息录入
   *  1.涉及到的角色 ：货运处 货运中心，电厂
   *  2.货运中心可以选择电厂
   *  3.电厂只能选择电厂
   *
   *  modalclose:::组件关闭事件
   *
   * @auther zhangQ
   * @date 2018/2/2 10:53
   **/
  import { addPowerStock, getPowerUserList, getPowerStockByDate } from '@api/backEnd/inventory'
  // import { getuserinfo } from "api/user"
  // import { parseTime } from 'utils'
  // import Cookies from 'js-cookie'
  import moment from 'moment'
  import _ from 'lodash'
  import { mapGetters } from 'vuex'
  //  const moment = require('moment')

  export default {
    name: 'addInventory',
    data () {
      let startDateOption = {
        disabledDate (date) {
          return date && date.valueOf() > Date.now()
        }
      }
      let dateValueEnable = true
      let isDcShow = false
      let modalShow = false
      let userId = ''
      let userName = ''
      let roles = ''
      let addInfo = {
        startDateValue: moment().format('YYYY年MM月DD日'),
        poweruserName: '',
        xhl: 0,
        kcl: 0,
        ddl: 0,
        lastQuarterDemand: 0,
        nextQuarterDemand: 0
      }
      let addInfoDefault = {} // 添加默认信息
      let addInfoRule = {
        xhl: [
          {
            trigger: 'blur',
            whitespace: true,
            validator (rule, value, callback) {
              value = +value
              let noExistError = '消耗量大于等于0'
              let reg = /^[0-9]\d*(\.\d+)?$/i
              if (!reg.test(value)) {
                callback(new Error(noExistError))
                return
              }
              callback()
            }
          }
        ],
        kcl: [
          {
            trigger: 'blur',
            whitespace: true,
            validator (rule, value, callback) {
              value = +value
              let noExistError = '库存量大于0'
              let reg = /^[0-9]\d*(\.\d+)?$/i
              if (!reg.test(value) || !value) {
                callback(new Error(noExistError))
                return
              }
              callback()
            }
          }
        ],
        ddl: [
          {
            trigger: 'blur',
            whitespace: true,
            validator (rule, value, callback) {
              value = +value
              let noExistError = '到达量大于等于0'
              let reg = /^[0-9]\d*(\.\d+)?$/i
              if (!reg.test(value)) {
                callback(new Error(noExistError))
                return
              }
              callback()
            }
          }
        ],
        lastQuarterDemand: [
          {
            trigger: 'blur',
            whitespace: true,
            validator (rule, value, callback) {
              value = +value
              let noExistError = '本季度需求量大于等于0'
              let reg = /^[0-9]\d*(\.\d+)?$/i
              if (!reg.test(value)) {
                callback(new Error(noExistError))
                return
              }
              callback()
            }
          }
        ],
        nextQuarterDemand: [
          {
            trigger: 'blur',
            whitespace: true,
            validator (rule, value, callback) {
              value = +value
              let noExistError = '下季度需求量大于等于0'
              let reg = /^[0-9]\d*(\.\d+)?$/i
              if (!reg.test(value)) {
                callback(new Error(noExistError))
                return
              }
              callback()
            }
          }
        ]
      }
      let userNamelist = []
      let datas = {
        startDateOption,
        dateValueEnable,
        isDcShow,
        roles,
        userId,
        userName,
        addInfo,
        addInfoRule,
        addInfoDefault,
        userNamelist,
        modalShow
      }
      return datas
    },
    props: {
      show: { // 显示
        type: Boolean
      },
      operaType: { // 操作类型，add，edit
        type: String,
        default: 'add'
      },
      inventory: { // 要录入的信息
        type: Object,
        default () {
          // 默认信息
          return {
            startDateValue: moment().format('YYYY年MM月DD日'),
            poweruserName: '',
            xhl: 0,
            kcl: 0,
            ddl: 0,
            lastQuarterDemand: 0,
            nextQuarterDemand: 0
          }
        }
      }
    },
    methods: {
      /**
       * TODO(提交操作)
       * @param operatorType:::操作类型
       * @date 2018/2/2 11:19
       **/
      submitAdd (operatorType) {
        this.$refs['addInfo'].validate((valid) => {
          if (valid) {
            this.saveAddInfo()
          } else {
            this.$Message.error('请正确填写数据！')
          }
        })
      },
      saveAddInfo () {
        if (!this.addInfo.startDateValue) {
          this.$Message.error('请正确日期！')
          return
        }
        // let nowStock = parseFloat(+this.addInfo.ddl + +this.addInfo.kcl - +this.addInfo.xhl).toFixed(2)
        if (!this.addInfo.poweruserName && this.userNamelist && this.userNamelist.length > 0) {
          this.$Message.error('请正选择电厂！')
          return
        }
        let thisuserId = _.result(_.find(this.userNamelist, { 'userName': String(this.addInfo.poweruserName) }), 'userId')
        // let userName = this.userName
        let param = {
          stockTime: moment(this.addInfo.startDateValue).format('YYYY-MM-DD HH:mm:ss'),
          yesterdayStock: +this.addInfo.kcl, // 今日库存
          yesterdayArrive: +this.addInfo.ddl,
          yesterdayConsume: +this.addInfo.xhl,
          nowStock: +this.addInfo.kcl,
          userName: this.addInfo.poweruserName ? this.addInfo.poweruserName : this.userName,
          userId: thisuserId ? thisuserId : this.userId,
          lastQuarterDemand: this.addInfo.lastQuarterDemand,
          nextQuarterDemand: this.addInfo.nextQuarterDemand
        }
        addPowerStock(param).then(res => {
          if (+res.data.isSuccess === 1) {
            this.$Message.success('添加成功')
            this.goBack()
          } else {
            this.$Message.error('添加失败请重试！')
          }
        })
      },
      /**
       * TODO(回归默认设置)
       * @auther zhangQ
       * @date 2018/2/2 11:22
       **/
      goBack () {
        this.modalShow = false
      },
      /**
       * TODO(获取电厂数据)
       * @param
       * @auther zhangQ
       * @date 2018/2/4 14:11
       **/
      getPowerUserList () {
        // 获取电厂数据
        this.userNamelist = []
        getPowerUserList().then(res => {
          if (res.data.isSuccess === 1) {
            this.userNamelist = res.data.data
          }
        })
      },
      /**
       * TODO(弹框执行函数)
       * @auther zhangQ
       * @date 2018/2/2 11:42
       **/
      executeShow () {
        // 通过角色判断是否显示电厂选择
        this.userId = this.currentUser.userId
        this.userName = this.currentUser.loginName
        this.roles = this.currentUser.role
        this.addInfo = JSON.parse(JSON.stringify(this.inventory))
        let userRoles = this.roles
        // 电厂
        if (userRoles && _.includes(userRoles, '电厂')) {
          this.isDcShow = false
          // 操作模式
          if (this.operaType === 'add') {
            this.dateValueEnable = true
            this.addInfo.poweruserName = this.userName
          } else if (this.operaType === 'edit') {
            // 编辑模式，不能选择电厂
            this.dateValueEnable = false
          }
        }
        // 货运中心
        if (userRoles && _.includes(userRoles, '货运中心')) {
          this.isDcShow = true
          // 操作模式
          if (this.operaType === 'add') {
            this.dateValueEnable = true
            this.getPowerUserList()
          } else if (this.operaType === 'edit') {
            // 编辑模式，不能选择电厂
            this.isDcShow = false
            this.dateValueEnable = false
          }
        }
        this.getHistoryData({
          stockTime: moment(this.addInfo.startDateValue).format('YYYY-MM-DD HH:mm:ss'),
          userName: this.addInfo.poweruserName
        })
        // 根据 poweruserName 获得历史数据
        this.$watch('addInfo.poweruserName', function (newVal, oldVal) {
          if (newVal) {
            // 获取历史记录 this.addInfo.poweruserName
            this.getHistoryData({
              stockTime: moment(this.addInfo.startDateValue).format('YYYY-MM-DD HH:mm:ss'),
              userName: this.addInfo.poweruserName
            })
          }
        })
      },
      /**
       * TODO(获得历史数据)
       * 1.根据选择的电厂获取历史数据
       * @param
       * @auther zhangQ
       * @date 2018/2/3 13:30
       **/
      getHistoryData (param) {
        if (!this.addInfo.poweruserName) {
          return
        }
        if (!param) {
          param = {
            stockTime: moment(this.addInfo.startDateValue).format('YYYY-MM-DD HH:mm:ss'),
            userName: this.addInfo.poweruserName
          }
        }
        if (this.operaType === 'add') {
          // 新增模式时间要减少一天
          // param.stockTime = moment(param.stockTime).subtract(1, 'days').format('YYYY-MM-DD HH:mm:ss')
          param.stockTime = moment(param.stockTime).format('YYYY-MM-DD HH:mm:ss')
        } else if (this.operaType === 'edit') {
        }
        getPowerStockByDate(param).then((response) => {
          let resData = response.data
          if (+resData.isSuccess === 1) {
            this.addInfo = Object.assign({}, this.addInfo, {
              id: resData.data.id,
              //              startDateValue: moment(resData.data.stockTime).format('YYYY年MM月DD日'),
              poweruserName: resData.data.userName,
              xhl: resData.data.yesterdayConsume,
              kcl: this.addInfo.kcl ? this.addInfo.kcl : 0,
              ddl: this.addInfo.ddl ? this.addInfo.ddl : 0,
              lastQuarterDemand: resData.data.lastQuarterDemand ? resData.data.lastQuarterDemand : 0,
              nextQuarterDemand: resData.data.nextQuarterDemand ? resData.data.nextQuarterDemand : 0
            })
          } else {
            // 如果错误 回到默认设置
            this.addInfo.xhl = 0
            this.addInfo.kcl = 0
            this.addInfo.ddl = 0
            this.addInfo.lastQuarterDemand = 0
            this.addInfo.nextQuarterDemand = 0
          }
        })
      }
    },
    watch: {
      show (val) {
        if (val) {
          this.modalShow = true
        }
      },
      modalShow (val, oldval) {
        if (val) {
          this.executeShow()
        } else {
          this.$emit('modalclose')
        }
      }
    },
    mounted () {
    },
    computed: {
      ...mapGetters(['currentUser'])
    }
  }
</script>
<style scoped>

</style>
